package com.jt.common.net;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 模拟一个简易的Tomcat
 * 基于java中的网络编程实现(java.net)
 * 1)网络服务端(ServerSocket)
 * 2)网络客户端(Socket)
 */
public class Tomcat {
    public static void main(String[] args) throws IOException {
        //1、创建服务(例如：启动nacos)，并在9999端口进行监听
        //网络中计算机的唯一标识：ip
        //计算机中应用程序的唯一标识：port
        ServerSocket server = new ServerSocket(9999);
        System.out.println("server start......");
        //2、启动服务监听
        while (true) {
            //监听客户端的链接
            Socket socket = server.accept();//阻塞方法
            //创建输出流对象，向客户端输出hello Client
            OutputStream outputStream = socket.getOutputStream();
//            outputStream.write("hello client".getBytes());
            byte[] responseContent = ("HTTP/1.1 200 OK \r\n" +
                    "Content-Type: text/html;charset=utf-8 \r\n" +
                    "\r\n" +
                    "<h1>hello, Client</h1>").getBytes(StandardCharsets.UTF_8);
            outputStream.write(responseContent);
            outputStream.flush();
        }
    }
}
